import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Image,
} from 'react-native';
import { useCartStore } from '../../store/CartStore';
import { cartItem } from '../../models/CartModel';
import { useNavigation } from '@react-navigation/native';
import { useToast } from '../../components/MyToast/useToasr';

// 购物车商品类型定义
// interface CartItem {
//   id: string;
//   title: string;
//   price: number;
//   tag: string;
//   image: string;
//   selected: boolean;
// }

const CartSreen = () => {
  const { cartList, cartChange, cartSelectAll } = useCartStore();

  // 全选状态
  const [selectAll, setSelectAll] = useState(false);

  useEffect(() => {
    setSelectAll(cartList.every(node => node.status) && cartList.length > 0);
  }, []);

  // 切换商品选中状态
  const toggleItemSelection = (item: cartItem) => {
    const obj = { ...item, status: !item.status };
    cartChange(obj);
    setSelectAll(cartList.every(node => node.status));
  };

  // 改变商品数量
  const changeItemNum = (item: cartItem, num: number) => {
    const obj = { ...item, num: item.num + num };
    cartChange(obj);
  };

  // 切换全选状态
  const toggleSelectAll = () => {
    const newSelectAll = !selectAll;
    setSelectAll(newSelectAll);
    cartSelectAll(newSelectAll);
  };

  // 计算选中商品的总价
  const calculateTotal = () => {
    return cartList
      .filter(item => item.status)
      .reduce((total, item) => total + item.price * item.num, 0);
  };

  const navigater = useNavigation();
  const toast = useToast();
  // 处理结算
  const handleCheckout = () => {
    // 这里添加结算逻辑
    console.log(
      '去结算',
      cartList.filter(item => item.status),
    );
    if (cartList.filter(item => item.status).length > 0) {
      navigater.navigate('Pay');
      return;
    } else {
      toast.warning('请选择商品');
      return;
    }
  };

  return (
    <View style={styles.container}>
      <ScrollView style={styles.scrollView}>
        {cartList.map(item => (
          <View key={item.id} style={styles.itemContainer}>
            <TouchableOpacity
              style={styles.checkbox}
              onPress={() => toggleItemSelection(item)}
              activeOpacity={0.7}
            >
              {item.status ? (
                <View style={styles.checkboxSelected}>
                  <Text style={styles.checkIcon}>✓</Text>
                </View>
              ) : (
                <View style={styles.checkboxUnselected} />
              )}
            </TouchableOpacity>

            <View style={styles.itemContent}>
              <Image
                style={styles.imagePlaceholder}
                source={{
                  uri: item.cover,
                }}
              />
              <View style={styles.itemDetails}>
                <Text style={styles.itemTitle} numberOfLines={2}>
                  {item.title}
                </Text>
                <Text style={styles.itemTag}>实战</Text>
                <View style={styles.itemPriceContainer}>
                  <Text style={styles.itemPrice}>¥{item.price.toFixed(2)}</Text>
                  <View style={styles.buttonsContainer}>
                    <Text
                      style={styles.button}
                      onPress={() => {
                        if (item.num <= 1) {
                          return;
                        }
                        changeItemNum(item, -1);
                      }}
                    >
                      -
                    </Text>
                    <Text style={styles.countText}>{item.num}</Text>
                    <Text
                      style={styles.button}
                      onPress={() => changeItemNum(item, +1)}
                    >
                      +
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          </View>
        ))}
      </ScrollView>

      <View style={styles.footer}>
        <View style={styles.footerLeft}>
          <TouchableOpacity
            style={styles.checkbox}
            onPress={toggleSelectAll}
            activeOpacity={0.7}
          >
            {selectAll ? (
              <View style={styles.checkboxSelected}>
                <Text style={styles.checkIcon}>✓</Text>
              </View>
            ) : (
              <View style={styles.checkboxUnselected} />
            )}
          </TouchableOpacity>
          <Text style={styles.selectAllText}>全选</Text>
        </View>

        <View style={styles.footerCenter}>
          <Text style={styles.totalText}>
            合计: ¥{calculateTotal().toFixed(2)}
          </Text>
        </View>

        <TouchableOpacity
          style={styles.checkoutButton}
          onPress={handleCheckout}
          activeOpacity={0.7}
        >
          <Text style={styles.checkoutButtonText}>去结算</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
  scrollView: {
    flex: 1,
  },
  itemContainer: {
    flexDirection: 'row',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#F0F0F0',
    alignItems: 'center',
  },
  checkbox: {
    marginRight: 12,
  },
  checkboxUnselected: {
    width: 20,
    height: 20,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#CCCCCC',
  },
  checkboxSelected: {
    width: 20,
    height: 20,
    borderRadius: 10,
    backgroundColor: '#007aff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkIcon: {
    color: '#FFFFFF',
    fontSize: 12,
    fontWeight: 'bold',
  },
  itemContent: {
    flex: 1,
    flexDirection: 'row',
  },
  imagePlaceholder: {
    width: 100,
    height: 120,
    // backgroundColor: '#007aff',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  imageText: {
    color: '#FFFFFF',
    fontSize: 24,
    fontWeight: 'bold',
  },
  itemDetails: {
    flex: 1,
    justifyContent: 'space-between',
  },
  itemTitle: {
    fontSize: 16,
    lineHeight: 22,
    color: '#333333',
    marginBottom: 8,
  },
  itemTag: {
    fontSize: 12,
    color: '#666666',
    marginBottom: 8,
  },
  itemPriceContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  itemPrice: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#FF0000',
  },
  footer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: '#F0F0F0',
    backgroundColor: '#FFFFFF',
  },
  footerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 16,
  },
  selectAllText: {
    fontSize: 16,
    color: '#333333',
  },
  footerCenter: {
    flex: 1,
  },
  totalText: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#FF0000',
  },
  checkoutButton: {
    backgroundColor: '#FF0000',
    paddingHorizontal: 24,
    paddingVertical: 10,
    borderRadius: 4,
  },
  checkoutButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: 'bold',
  },
  buttonsContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  countText: {
    marginHorizontal: 10,
  },
  button: {
    width: 20,
    height: 20,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#CCCCCC',
    textAlign: 'center',
    fontSize: 20,
    lineHeight: 20,
  },
});

export default CartSreen;
